﻿using System;
using System.IO;
using System.Text;
using System.Xml.Serialization;

namespace SPFluid.Core.Utilities
{
    public class SerializationUtility
    {
        public static string SerializeObject(object obj)
        {
            if (obj == null)
            {
                return string.Empty;
            }

            using (var stream = new MemoryStream())
            {
                var serializer = new XmlSerializer(obj.GetType());
                serializer.Serialize(stream, obj);
                stream.Position = 0;
                var bytes = new byte[stream.Length];
                stream.Read(bytes, 0, bytes.Length);
                return Encoding.UTF8.GetString(bytes);
            }
        }

        public static object DeserializeObject(Type aType, string xmlString)
        {
            if (string.IsNullOrEmpty(xmlString))
            {
                var ctor = aType.GetConstructor(new Type[0]);
                return ctor != null ? ctor.Invoke(null) : null;
            }

            using (var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xmlString)))
            {
                var xmlSerializer = new XmlSerializer(aType);
                return xmlSerializer.Deserialize(memoryStream);
            }
        }

        public static T DeserializeObject<T>(string xmlString)
            where T : class, new()
        {
            if (string.IsNullOrEmpty(xmlString))
            {
                return new T();
            }

            using (var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xmlString)))
            {
                var xmlSerializer = new XmlSerializer(typeof(T));
                return (T)xmlSerializer.Deserialize(memoryStream);
            }
        }
    }
}
